/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.jasonchoi.gateway.swagger;

import com.jasonchoi.gateway.LamdbaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Component
@Primary
@AllArgsConstructor
public class SwaggerResourceConfig implements SwaggerResourcesProvider {

    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;

    @Autowired
    private Environment environment;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));

      List<RouteDefinition> routeDefinitions = gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
                                                       .collect(Collectors.toList());
      LamdbaUtils.forEach(routeDefinitions, (index, route) -> {
        route.getPredicates().stream()
             .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
             .forEach(predicateDefinition -> {
               String serviceId = route.getId();
               String location = predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
                                                    .replace("**", "v2/api-docs");
               String groupNames = environment.getProperty(String.format("spring.cloud.gateway.routes.[%s].swagger-groupname", index));
               resources.add(swaggerResource(serviceId + "所有接口", location));
               if (StringUtils.isNotBlank(groupNames)) {
                 //在这里处理分组的swagger，可以通过配置文件的方式配置需要分组的微服务，然后单独处理
                 for (String groupName : groupNames.split(",")) {
                   resources.add(swaggerResource(
                       String.format("%s__%s", serviceId, groupName),
                       String.format("%s?group=%s", location, groupName)));
                 }
               }
             });
      });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        log.info("name:{},location:{}",name,location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
